package com.loong.controller;

import com.loong.pojo.Address;
import com.loong.pojo.User;
import com.loong.service.AddressService;
import com.loong.service.impl.AddressServiceImpl;
import com.loong.utils.Constants;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/address")
public class AddressController extends BaseServlet{

    public String show(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");
        if(user == null){
            request.setAttribute("msg","需要先登录");
            return Constants.REDIRECT + "/login.jsp";
        }
        Integer uid = user.getUid();
        AddressService addressService = new AddressServiceImpl();
        List<Address> address = addressService.findAddressByUid(uid);
        request.setAttribute("address",address);
        return Constants.FORWARD + "/self_info.jsp";
    }

    public String add(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        Map<String, String[]> map = request.getParameterMap();
        Address address = new Address();
        BeanUtils.populate(address, map);
        address.setDefaultAddress(0);
        AddressService addressService = new AddressServiceImpl();
        addressService.saveAddress(address);

        return Constants.FORWARD + "/address?method=show";
    }

    public String delete(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        String aid = request.getParameter("aid");
        AddressService addressService = new AddressServiceImpl();
        addressService.deleteAddressByAid(aid);

        return Constants.FORWARD + "/address?method=show";
    }

    public String setDefault(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        String aid = request.getParameter("aid");
        AddressService addressService = new AddressServiceImpl();
        addressService.setAddressToDefault(aid);
        return Constants.FORWARD + "/address?method=show";
    }

    public String update(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        Map<String, String[]> map = request.getParameterMap();
        Address address = new Address();
        BeanUtils.populate(address, map);
        AddressService addressService = new AddressServiceImpl();
        addressService.updateAddress(address);
        return Constants.FORWARD + "/address?method=show";
    }
}
